#!/usr/bin/env ruby
#
#  Created by Christopher Biagini on 2007-07-08.
#  Copyright (c) 2007. All rights reserved.

require 'rbosa' # from <http://rubyosa.rubyforge.org/>
require 'json'  # from <http://json.rubyforge.org/>

# Standard libraries
require 'webrick'
include WEBrick

itunes = OSA.app('iTunes')

module OSA::ITunes
  class Application
    def to_json(*a)
      {
        'sound_volume'   => (self.sound_volume / 10.0).round,
        'current_track'  => self.current_track,
        'player_state'   => self.player_state
      }.to_json(*a)
    end
  end

  class Track
    def to_json(*a)
      {
        'album'   => self.album,
        'artist'  => self.artist,
        'rating'  => (self.rating / 20.0).round,
        'name'    => self.name
      }.to_json(*a)
    end
  end  
end

server = HTTPServer.new(
  :Port => 1984, 
  :DocumentRoot => Dir::pwd + "/www/",
  :Logger => Log.new(nil, BasicLog::WARN),
  :AccessLog => []
  )
  
server.mount_proc('/itunes') do |req, resp|
  case req.query['action']
  when "info"
    # fall through, nothing here to do now, since we always respond with the current state
  when "playpause"
    itunes.playpause
  when "back_track"
    itunes.back_track
  when "next_track"
    itunes.next_track
  when "vol_up"
    itunes.sound_volume += 10.0
    itunes.sound_volume = (itunes.sound_volume / 10.0).round * 10.0
  when "vol_down"
    itunes.sound_volume -= 10.0
    itunes.sound_volume = (itunes.sound_volume / 10.0).round * 10.0
  when "rat_up"
    itunes.current_track.rating += 20.0
    itunes.current_track.rating = (itunes.current_track.rating / 20.0).round * 20.0
  when "rat_down"
    itunes.current_track.rating -= 20.0
    itunes.current_track.rating = (itunes.current_track.rating / 20.0).round * 20.0
  end
  
  resp.body = JSON.generate(itunes) # always respond with current state
end
  
trap("INT"){ server.shutdown }

server.start
